package com.lllmark.lllmarkDemo.rest;

import com.lllmark.lllmarkDemo.Utils.MyStringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuxiangZhang
 * @data 2024/5/11
 */
@Slf4j
public class BaseController {

    /**
     * 返回数据的格式
     * @param code
     * @param msg
     * @param o
     * @return
     */
    public Map<String, Object> result(Integer code, String msg, Object o){
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", code);
        hashMap.put("message", msg);
        hashMap.put("data", o);
        return hashMap;
    }

    /**
     * 访问成功响应数据
     * @param o
     * @return
     */
    public Map<String, Object> success(Object o){
        return result(200, null, o);
    }

    /**
     * 访问失败返回数据
     * @param code
     * @param msg
     * @return
     */
    public Map<String, Object> failed(Integer code, String msg){
        return result(code, msg, null);
    }


    /**
     * 传输文件
     * @param response
     * @param filePath
     */
    protected void readFile(HttpServletResponse response, String filePath) {
        if (!new MyStringUtils().pathIsOk(filePath)) {
            return;
        }
        OutputStream out = null;
        FileInputStream in = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return;
            }
            in = new FileInputStream(file);
            byte[] byteData = new byte[1024];
            out = response.getOutputStream();
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("读取文件异常", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("IO异常", e);
                }
            }
        }
    }



}
